package com.edu.bean;
/*
 * @Author:princess
 * @Date 2023/10/26 10 26 9:38
 *
 */

/*
 * 模仿spring 通过反射实现 IOC容器
 */

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyIOC {
    private Map<String,Object> map = new HashMap<>();//真正用于存储bean的一个容器

    public MyIOC(String path){
        Properties properties = new Properties();//创建集合 用于加载配置文件名
        InputStream ins = MyIOC.class.getClassLoader().getResourceAsStream(path);
        try {
            properties.load(ins);
            Set<String> keys = properties.stringPropertyNames();
            for (String key : keys) {
                String className = properties.getProperty(key);//获取所有键所对应的值
                Class clazz = Class.forName(className);
                Constructor constructor = clazz.getDeclaredConstructor();
                Object o = constructor.newInstance();
                map.put(key,o);
            }
        } catch (IOException e) {
            System.out.println("请检查容器配置文件的地址");
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            System.out.println("找不到对应的类型");
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            System.out.println("检测不到无参构造方法");
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public Object getBean(String name){
        return map.get(name);
    }

    public Object getBean(Class clazz){
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            Object o = map.get(key);
            if (o.getClass().equals(clazz)){
                return o;
            }
        }
        return null;
    }
}
